import React, { useState, useImperativeHandle, forwardRef } from 'react';

import { IFilter } from '@/pages/SelfQuery/type';
import { VISUALTYPES, FILTER_OPERATOR, DATA_ACTION_TYPE } from '@/pages/SelfQuery/constants';

import { DatePicker, Tag } from 'antd';
import moment from 'moment';

interface DateFilterProps {
  onCustomSelectFilter: (key: string, filters: IFilter[] | undefined) => void;
  name: string;
  text: string;
  defaultValue: any;
  ref?: any;
  cRef?: any;
  defaultType: string;
}

const DateFilter: React.FC<DateFilterProps> = (props, ref) => {
  const { onCustomSelectFilter, name, text, cRef, defaultValue, defaultType } = props;
  const [filtersTime, setFiltersTime] = useState<any>(defaultValue); // 选择的过滤时间
  const [filtersTimeType, setFiltersTimeType] = useState<string>(defaultType); // 选择的过滤时间类型

  // 重置方法
  useImperativeHandle(cRef, () => ({
    clear: () => {
      setFiltersTime([]);
    },
  }));

  // 日期选择发生变化 获得筛选表单的值
  const onDateChange = (dates: any, type: string) => {
    setFiltersTimeType(type);
    setFiltersTime(dates);
    if (dates) {
      let start = '';
      let end = '';
      const startTs = '00:00:00';
      const endTs = '23:59:59.999';
      if (dates.length > 0) {
        start = `${moment(dates[0]).format('yyyy-MM-DD')} ${startTs}`;
        end = `${moment(dates[1]).format('yyyy-MM-DD')} ${endTs}`;
      }

      if (start == '' && end == '') {
        onCustomSelectFilter(name, undefined);
        return;
      }

      // 获得传递的日期参数
      let filters: IFilter[] = [];
      const filter: IFilter = {
        name,
        column: `cast(${name} as TIMESTAMP)`,
        operator: FILTER_OPERATOR.BETWEEN,
        type: 'filter',
        sqlType: 'STRING',
        value: [`'${start}'`, `'${end}'`],
        action: DATA_ACTION_TYPE.filter,
        label: type,
        visualType: VISUALTYPES.Date,
        isCustomFilter: true,
      };
      filters.push(filter);
      onCustomSelectFilter(name, filters);
    }
  };

  // 自定义时间选择框底部 时间区间样式
  const ranges = () => {
    return (
      <div style={{ textAlign: 'left' }}>
        <Tag
          color={filtersTimeType === '自定义' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([], '自定义');
          }}
        >
          自定义
        </Tag>
        <Tag
          color={filtersTimeType === '本日' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment(), moment()], '本日');
          }}
        >
          本日
        </Tag>
        <Tag
          color={filtersTimeType === '本周' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().startOf('week'), moment().endOf('week')], '本周');
          }}
        >
          本周
        </Tag>
        <Tag
          color={filtersTimeType === '本月' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().startOf('month'), moment().endOf('month')], '本月');
          }}
        >
          本月
        </Tag>
        <Tag
          color={filtersTimeType === '本年' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().startOf('year'), moment().endOf('year')], '本年');
          }}
        >
          本年
        </Tag>
        <Tag
          color={filtersTimeType === '近七天' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().subtract('days', 7), moment().subtract('days', 1)], '近七天');
          }}
        >
          近七天
        </Tag>
        <Tag
          color={filtersTimeType === '近30天' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().subtract('days', 30), moment().subtract('days', 1)], '近30天');
          }}
        >
          近30天
        </Tag>
        <Tag
          color={filtersTimeType === '近一年' ? 'blue' : ''}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            onDateChange([moment().subtract('days', 365), moment().subtract('days', 1)], '近一年');
          }}
        >
          近一年
        </Tag>
      </div>
    );
  };

  return (
    <div
      style={{
        display: 'flex',
        marginBottom: 24,
      }}
    >
      <span
        style={
          text.length >= 4
            ? {
                flex: '0 0 80px',
                lineHeight: '32px',
                overflow:'hidden',
                textOverflow:'ellipsis',
                whiteSpace:'nowrap',
              }
            : {
                flex: '0 0 50px',
                lineHeight: '32px',
                overflow:'hidden',
                textOverflow:'ellipsis',
                whiteSpace:'nowrap',
              }
        }
      >
        {text}
      </span>
      <DatePicker.RangePicker
        allowClear={false}
        value={filtersTime}
        renderExtraFooter={ranges}
        onChange={(dates) => {
          onDateChange(dates, '自定义');
        }}
      />
    </div>
  );
};

// @ts-ignore
export default forwardRef(DateFilter);
